package top.tenebrous.yzl.im.server;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import top.tenebrous.yzl.im.factory.message.MessageFactory;
import top.tenebrous.yzl.im.utils.WebSocketUtils;

/**
 * 服务端之间通信，用于多台服务之间session共享，提高并发的能力
 * 主要利用websocket客户端与服务端互联，以一定的规则，分发session与各个服务端机器上
 * 该websocket，主要是维持服务端之间的共享数据，利用一定的规则，将session传递给对应的服务端
 *
 * @author yazhang6
 */
@Slf4j
@Component
public class WebSocketHandlerServer extends TextWebSocketHandler {

    @Autowired
    private MessageFactory messageFactory;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String clientId =(String) session.getAttributes().get("clientId");
        // 将session存入池中
        WebSocketUtils.addServerSession(clientId, session);

        log.info("服务端 --> [{}] 新的客户端加入im集群", clientId);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
        } catch (Exception ignored) {

        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String clientId =(String) session.getAttributes().get("clientId");
        log.info("服务端 --> 客户端[{}]下线 --> 下线原因:[{}]", clientId, JSON.toJSONString(status));
        WebSocketUtils.removeServerSession(session);
    }
}